package com.wlcb.jpower.chat.server;


import com.wlcb.jpower.chat.server.handler.ChatInterceptHandler;
import com.wlcb.jpower.chat.server.handler.ChatServerHandler;
import com.wlcb.jpower.constant.ChatConfigConstant;
import com.wlcb.jpower.properties.JpowerChatProperties;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.NettyRuntime;
import io.netty.util.concurrent.DefaultThreadFactory;
import io.netty.util.concurrent.UnorderedThreadPoolEventExecutor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Component;

/**
 * netty服务启动类
 */
@Slf4j
@Component("chatServerApp")
@DependsOn
public class ChatServerApp {

    @Autowired
    private JpowerChatProperties properties;

    private final EventLoopGroup bossGroup = new NioEventLoopGroup();
    private final EventLoopGroup workGroup = new NioEventLoopGroup();
    UnorderedThreadPoolEventExecutor business = new UnorderedThreadPoolEventExecutor(NettyRuntime.availableProcessors()*2 , new DefaultThreadFactory("jc-business"));

    @SneakyThrows(InterruptedException.class)
    public void startApp() {
        log.info("jpower-chat-server服务启动中.......");
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(bossGroup, workGroup)
                .channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO))
                .option(ChannelOption.SO_BACKLOG, 1024)
                .childOption(ChannelOption.TCP_NODELAY, true)
                .childOption(ChannelOption.SO_KEEPALIVE, true)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel channel) throws Exception {
                        ChannelPipeline pipeline = channel.pipeline();
                        pipeline.addLast("HttpServerCodec", new HttpServerCodec());
                        pipeline.addLast("HttpObjectAggregator", new HttpObjectAggregator(1024 * 1024 * 8));
                        pipeline.addLast("IdleStateHandler", new IdleStateHandler(properties.getIdleTimeRead(),
                                properties.getIdleTimeWrite(),
                                properties.getIdleTimeAll()));
                        pipeline.addLast("ChatInterceptHandler", new ChatInterceptHandler());
                        pipeline.addLast("WebSocketServerProtocolHandler", new WebSocketServerProtocolHandler(ChatConfigConstant.ChatAppConstant.CHAT, null, true, 65536 * 10));
                        pipeline.addLast(business, "ChatServerHandler", new ChatServerHandler());
                    }
                });
        ChannelFuture future = bootstrap.bind(properties.getServerPort()).sync();
        future.addListener((ChannelFutureListener) channelFuture -> {
            if (channelFuture.isSuccess()) {
                log.info("jpower-chat-server服务启动完成：port：{}", properties.getServerPort());
            }
        });
    }

    public void stop() {
        log.info("jpower-chat-server服务停止......");
        bossGroup.shutdownGracefully();
        workGroup.shutdownGracefully();

    }
}
